<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2025/2/20
 * Time: 17:46
 */

namespace app\modules\setting\controllers\office;


use app\common\controllers\AdminOptionsController;
use app\common\enum\EtcOfficeProductSelected_SendStatusEnum;
use app\common\helper\CommonHelper;
use app\models\EtcOfficeProductSelected;
use app\modules\setting\configs\office\SelectedConfig;
use app\modules\setting\models\seller\EtcOfficeProductSelectedSearch;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

class SelectedController extends AdminOptionsController
{
    /**
     * @return array
     * 列表数据
     */
    public function actionIndex()
    {
        try {
            $searchModel = new EtcOfficeProductSelectedSearch();
            $dataProvider = $searchModel->searchOffice(Yii::$app->request->queryParams);
            $data = $dataProvider->getModels();
            if($data){
                $data = array_map(function($item){
                    $re = $item;
                    if(is_object($item)){
                        $re = $item->toArray();
                    }
                    $re['product_id'] = CommonHelper::getProductNameById($item['product_id']);
                    return $re;
                },$data);
            }
            return ArrayHelper::merge(["data" =>$data, "pagination" => $dataProvider->getPagination()],SelectedConfig::configIndex());
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }

    /**
     * @param $id
     * @return array
     * 修改接口
     */
    public function actionUpdate($id)
    {
        try {

            $model = $this->findModel($id);
            if($model->send_status!=EtcOfficeProductSelected_SendStatusEnum::DONE){
                throw new Exception("商家未发货，无法签收");
            }
            $model->send_status = EtcOfficeProductSelected_SendStatusEnum::SIGN;
            if(!$model->save()){
                throw new Exception(CommonHelper::getFirstErrorStr($model->errors));
            }
            return ["msg" => "签收成功"];
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }


    protected function findModel($id)
    {
        if (($model = EtcOfficeProductSelected::findOne($id)) !== null) {
            return $model;
        }

        throw new Exception('不存在的记录');
    }
}